package pb

import (
	"flag"
	"os"
	"path/filepath"
	"strings"

	"gitee.com/xuender/oils/base"
	"github.com/pelletier/go-toml"
)

func NewConfig(config string) *Config {
	return &Config{
		Config: config,
	}
}

func (p *Config) Parse() {
	cli := NewConfig(p.Config)
	flag.StringVar(&cli.Config, "config", p.Config, "配置文件")
	flag.StringVar(&cli.Command, "command", "", "命令")
	flag.Parse()

	if strings.HasPrefix(p.Config, "~") {
		path := base.Panic1(os.UserHomeDir())
		p.Config = filepath.Join(path, p.Config[2:])
	}

	p.Config = base.Panic1(filepath.Abs(p.Config))
	fileInfo, err := os.Stat(p.Config)

	if err == nil && !fileInfo.IsDir() {
		file := base.Panic1(os.Open(p.Config))
		defer file.Close()

		decoder := toml.NewDecoder(file)
		base.Panic(decoder.Decode(p))
	}

	if cli.Command != "" && p.Command == "" {
		p.Command = cli.Command
	}
}
